import { v4 as uuidv4 } from 'uuid';
import type { IRectification } from '../../components/rectification/Content';
import { RECTIFICATION } from '../../components/rectification/Content';
import { CONFIG_KEYS } from '../../constants/config';
import { DATA_SOURCE, FILL_NAME, INodeState, LANHAI_SYSTEM, NODE_TYPE, RECTIFICATION_TEXT, TABLE_COLLECTION } from '../../constants/default';
import { now } from '../../util/helper';
import type { LanhaiFile } from '../types/file';
import type { w_zggk } from '../types/zggk';
import type { ILanhaiSpDef, IPipe, IRecordSchemas } from './interface';
import { Pipe } from './pipe';

export class Rectification extends Pipe implements IPipe {
  async import() {
    return Promise.resolve([]);
  }

  async export(sp_def: ILanhaiSpDef) {
    const { config } = this.data;
    const xczdx_ref_id = config[CONFIG_KEYS.F_XCZDX_REF_ID_]?.value || 'demo';

    const item: IRectification = config[RECTIFICATION]?.value;

    if (!item)
      return {};

    const data: IRecordSchemas = {
      w_zggk: {
        module: 'rectification',
        table: TABLE_COLLECTION.RECTIFICATION,
        path: FILL_NAME,
        main: true,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: RECTIFICATION_TEXT,
        table_name: TABLE_COLLECTION.RECTIFICATION,
      },
      w_sp_node: {
        module: 'node',
        table: TABLE_COLLECTION.SP_NODE,
        path: FILL_NAME,
        main: false,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SP_NODE,
      },
      w_sp_history: {
        module: 'record',
        table: TABLE_COLLECTION.SP_HISTORY,
        path: FILL_NAME,
        main: true,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SP_HISTORY,
      },
      w_zggk_ls: {
        module: 'rectification',
        table: TABLE_COLLECTION.RECTIFICATION_LS,
        path: FILL_NAME,
        main: false,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.RECTIFICATION_LS,
      },
      sys_file: {
        module: 'lanhai',
        table: TABLE_COLLECTION.SYS_FILE,
        path: LANHAI_SYSTEM,
        main: false,
        data: [],
        data_source: DATA_SOURCE.LANHAI_SYSTEM,
        pk: 'FILE_ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SYS_FILE,
      },
    };

    const time = now();

    const attachment = (item?.attachment ? item?.attachment : []).map((item) => {
      return {
        COVER_STATUS_: 'NO',
        CREATE_BY_: '1',
        CREATE_DEP_ID_: '1',
        CREATE_TIME_: time,
        DEL_STATUS_: 'undeleted',
        EXT_: item.ext,
        FILE_ID_: `${item.uid}`,
        FILE_NAME_: item.name,
        FILE_SYSTEM_: 'file',
        NEW_FNAME_: item.fileName,
        PATH_: item.fileName,
        TENANT_ID_: '1',
        TOTAL_BYTES_: item.size,
        UPDATE_TIME_: time,
        encrypt: 0,
      } as LanhaiFile;
    });

    const publish = (item?.publish ? item?.publish : []).map((item) => {
      return {
        COVER_STATUS_: 'NO',
        CREATE_BY_: '1',
        CREATE_DEP_ID_: '1',
        CREATE_TIME_: time,
        DEL_STATUS_: 'undeleted',
        EXT_: item.ext,
        FILE_ID_: `${item.uid}`,
        FILE_NAME_: item.name,
        FILE_SYSTEM_: 'file',
        NEW_FNAME_: item.fileName,
        PATH_: item.fileName,
        TENANT_ID_: '1',
        TOTAL_BYTES_: item.size,
        UPDATE_TIME_: time,
        encrypt: 0,
      } as LanhaiFile;
    });

    const inside = (item?.inside ? item?.inside : []).map((item) => {
      return {
        COVER_STATUS_: 'NO',
        CREATE_BY_: '1',
        CREATE_DEP_ID_: '1',
        CREATE_TIME_: time,
        DEL_STATUS_: 'undeleted',
        EXT_: item.ext,
        FILE_ID_: `${item.uid}`,
        FILE_NAME_: item.name,
        FILE_SYSTEM_: 'file',
        NEW_FNAME_: item.fileName,
        PATH_: item.fileName,
        TENANT_ID_: '1',
        TOTAL_BYTES_: item.size,
        UPDATE_TIME_: time,
        encrypt: 0,
      } as LanhaiFile;
    });

    // 需要导出的文件
    data.sys_file.data.push(...attachment, ...publish, ...inside);

    const rectification: w_zggk = {
      F_BJR_: item.user,
      F_DNTBG_: JSON.stringify(attachment.map(item => ({
        ...item,
        fileId: item.FILE_ID_,
        fileName: item.FILE_NAME_,
      }))),
      F_SHGKG_: JSON.stringify(publish.map(item => ({
        ...item,
        fileId: item.FILE_ID_,
        fileName: item.FILE_NAME_,
      }))),
      F_SXSM_: JSON.stringify(inside.map(item => ({
        ...item,
        fileId: item.FILE_ID_,
        fileName: item.FILE_NAME_,
      }))),
      F_XCZDX_REF_ID_: xczdx_ref_id,
      ID_: item.uuid,
      REF_ID_: '',
      PARENT_ID_: '',
      UPDATE_VERSION_: '',
      INST_ID_: '',
      INST_STATUS_: '',
      TENANT_ID_: '',
      CREATE_TIME_: now(),
      CREATE_BY_: '',
      UPDATE_BY_: '',
      UPDATE_TIME_: now(),
      CREATE_DEP_ID_: '',
      SERIAL_NUM_: 0,
      DEL_FLAG_: '',
    };

    // 组织整改公开
    data.w_zggk.data.push(rectification);

    // 业务说明
    // 导出情况只导出已处理状态数据
    // 已处理情况包含所有未通过数据

    // 获取当前节点信息, 节点不存在获取当前分组第一条
    const current_defs = sp_def[NODE_TYPE.RECTIFICATION];
    let current_index = 0;
    let current_def;
    // const current_def = item.node ? current_defs[+item.node] : current_defs[0];
    if (item.node) {
      current_index = current_defs.findIndex(_item => String(_item.ID_) === String(item.node));
      current_def = current_defs[current_index];
    }
    else {
      current_def = current_defs[current_index];
    }

    const next = current_defs[current_index + 1];
    // 节点ID
    const node_id = (!!item.node_id && item.node_id) || (uuidv4());
    // 关联ID
    const rel_id = item.uuid;
    // 审核记录ID
    const history_id = uuidv4();

    // 初始状态
    let state = item.state ? (item.state as INodeState) : INodeState.WAIT;

    // 状态未通过
    const fail = [INodeState.FAIL, INodeState.AGAIN_FAIL];

    if (fail.includes(state))
      state = INodeState.AGAIN_WAIT;

    // 组织流程节点
    data.w_sp_node.data.push({
      F_REL_ID_: rel_id,
      F_DEF_ID_: current_def?.ID_ || '',
      F_GROUP_ID_: current_def?.F_GROUP_ID_ || '',
      F_GROUP_NAME_: current_def?.F_GROUP_NAME_ || '',
      F_GROUP_KEY_: current_def?.F_GROUP_KEY_ || '',
      F_STATE_: state,
      F_SFDQJD_: '1',
      F_NEXT_: (next && next.ID_) || '',
      F_TYPE_: NODE_TYPE.RECTIFICATION,
      ID_: node_id,
      REF_ID_: '0',
      PARENT_ID_: '0',
      UPDATE_VERSION_: '',
      INST_ID_: '',
      INST_STATUS_: '',
      TENANT_ID_: '1',
      CREATE_TIME_: now(),
      CREATE_BY_: '',
      UPDATE_BY_: '',
      UPDATE_TIME_: now(),
      CREATE_DEP_ID_: '',
      SERIAL_NUM_: 1,
      DEL_FLAG_: '1',
    });

    // 组织审批记录
    data.w_sp_history.data.push({
      F_XCZDX_REF_ID_: xczdx_ref_id,
      F_SPYJ_: '',
      F_SPSM_: '',
      F_SMCL_: '',
      F_FSSJ_: now(),
      F_NODE_ID_: node_id,
      F_RELID_: rel_id,
      F_TYPE_: NODE_TYPE.RECTIFICATION,
      F_SHDW_: '',
      F_SHR_: '',
      F_SHDWMC_: '',
      F_SHRMC_: '',
      ID_: history_id,
      REF_ID_: '0',
      PARENT_ID_: '0',
      UPDATE_VERSION_: '',
      INST_ID_: '',
      INST_STATUS_: '',
      TENANT_ID_: '1',
      CREATE_TIME_: now(),
      CREATE_BY_: '',
      UPDATE_BY_: '',
      UPDATE_TIME_: now(),
      CREATE_DEP_ID_: '',
      SERIAL_NUM_: 1,
      DEL_FLAG_: '1',
    });

    const {
      F_BJR_,
      F_DNTBG_,
      F_SHGKG_,
      F_SXSM_,
    } = rectification;
    data.w_zggk_ls.data.push({
      F_SP_HISTORY_ID_: history_id,
      F_BJR_,
      F_DNTBG_,
      F_SHGKG_,
      F_SXSM_,
      ID_: uuidv4(),
      REF_ID_: '0',
      PARENT_ID_: '0',
      UPDATE_VERSION_: '',
      INST_ID_: '',
      INST_STATUS_: '',
      TENANT_ID_: '1',
      CREATE_TIME_: now(),
      CREATE_BY_: '',
      UPDATE_BY_: '',
      UPDATE_TIME_: now(),
      CREATE_DEP_ID_: '',
      SERIAL_NUM_: 1,
      DEL_FLAG_: '1',
    });

    return Promise.resolve(data);
  }
}
